package com.hexanet.server.service.impl;


import com.hexanet.bom.Cell;
import com.hexanet.bom.Server;
import com.hexanet.commons.EnergyCommonsService;
import com.hexanet.server.dao.CellDao;
import com.hexanet.server.exception.EnergyLimitException;
import com.hexanet.server.service.EnergyService;

public class EnergyServiceImpl implements EnergyService {
    
    CellDao cellDao = new CellDao();
    EnergyCommonsService energyCommonsService = new EnergyCommonsService();


    @Override
    public void updateSavedEnergy(Cell c) {
	
	energyCommonsService.calculateProducedEnergy(c);
	cellDao.save(c);
	
    }

   

    /**
     * this method has only to be called when an upgrade on a server or the firewall is done
     * 
     */
    @Override
    public void updateProducedEnergyNetto(Cell c) throws EnergyLimitException {
	
	int result = 0;
	
	for(Server s : c.getServers())
	{
	    result += s.getConsumesEnergy();
	}
	
	result += c.getFirewall().getConsumesEnergy();
	
	int diff = c.getProducesEnergyBrutto() - result;
	
	if(diff <= 0)
	    throw new EnergyLimitException("You don't have enough resources to upgrade");
	
	c.setProducesEnergyNetto(diff);
	
    }

  
}
